// pages/contest/contest.js
const app = getApp();
const animationShowHeight = 300;
import {
  observer
} from '../../libs/observer';
import {
  action
} from '../../libs/mobx';
import async from '../../libs/async.js';
import Store from './contestStore';
import UploadStore from './upload/store.js';
import LoginStore from '../login/store.js';
import PhotoselectStore from '../photoselect/store.js';

import {
  proxy,
  getscene,
  getparamstr,
  reqHeader,
  isAuthorization
} from '../../utils/util.js';


import {
  encode
} from '../../libs/querystring/index.js';

let shareFlag =false;
Page(observer({
  props: {
    store: Store
  },

  /**
   * 页面的初始数据
   */
  data: {
    navbarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '', //导航栏 中间的标题
      background: 'linear-gradient(to bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0))',
      hasFilter: true,
      color: '#FFFFFF',
      btnStyle: 'white', //black, white
    },
    navBarHeight: app.globalData.height,
    // timestamp : true,
    animationData: {},
    showModalStatus: false,
    showTheme:false,
    photoListData: {
      cls: 'contestList'
    },
    sharePop:false,
    selectedCategoryId: '',
    workSource: 0,
    IPhoneX: app.globalData.isIphoneX
  },
  sharePopShow:function(){
    if (this.data.shareImgurl){
      this.setData({
        sharePop: true
      });
    }else{
      wx.showLoading({
        title: '图片获取中',
      });
      shareFlag=true
    }
    
  },
  closeSharePop:function(e){
    this.setData({
      sharePop: false
    });
    if (e.detail.makePoster){
      this.makePoster();
    }
  },
  makePoster:function(){
    wx.showLoading({
      title: '生成中...',
      mask:true
    });

    let me = this;

    getscene(Store.cur_contest.id, function (scene) {
      let cover_obj = {
        url: Store.cur_contest.appDetailUrl ? Store.cur_contest.appDetailUrl.baseUrl + '!p3' : Store.cur_contest.appUrl.baseUrl + '!p3'
      }
      let prize_obj = {
        url: 'https://node.500px.me/images/WeChat/quest.png'
      }
      let logo_obj = {
        url: 'https://node.500px.me/images/WeChat/500pxLogo.png'
      }
      let erweima_obj = {
        url: `https://node.500px.me/weChat/queryCodeImg?page=pages/contest/contest&scene=${scene}`
      }

      async.forEach([cover_obj, prize_obj, logo_obj, erweima_obj], (item, callback) => {
        wx.getImageInfo({
          src: item.url,
          success: function (res) {
            item.res = res;
            callback();
          },
          fail: function (e) {
            console.log(e)
          }
        });
      }, function () {
        let canvasWidth = app.globalData.screenWidth;
        let coverBoxHeight = 282 / 375 * canvasWidth;
        let canvasHeight = coverBoxHeight + 123;

        me.setData({
          canvasHidden: false,
          canvasHeight: canvasHeight
        }, () => {
          var context = wx.createCanvasContext('myCanvas');

          context.fillStyle = "#fff";
          context.fillRect(0, 0, canvasWidth + 10, canvasHeight + 10);

          let coverImgHeight = coverBoxHeight;
          let coverImgWidth = cover_obj.res.width / cover_obj.res.height * coverImgHeight;
          let coverLeft = (coverImgWidth - canvasWidth) / 2;
          let coverTop = 0;
          if (coverImgWidth < canvasWidth) {
            coverImgWidth = canvasWidth;
            coverImgHeight = cover_obj.res.height / cover_obj.res.width * coverImgWidth;
            coverLeft = 0;
            coverTop = (coverImgHeight - coverBoxHeight) / 2;
          };
          context.save();
          context.beginPath()
          context.rect(0, 0, canvasWidth, coverBoxHeight);
          context.fill();
          context.clip()
          context.drawImage(cover_obj.res.path, -coverLeft, -coverTop, coverImgWidth + 2, coverImgHeight);
          context.restore();

          context.rect(0, 0, canvasWidth+2, coverBoxHeight)
          context.setFillStyle("rgba(0,0,0,0.5)");
          context.fill();

          context.setFontSize(20);
          context.weight = "bold";
          context.setTextAlign('center');
          context.setTextBaseline('bottom');
          context.setFillStyle("#fff");

          //折行
          let contestTitle = Store.cur_contest.title;
          let rowCut = [];
          if (context.measureText(contestTitle).width < (canvasWidth - 32)){
            context.fillText(contestTitle, canvasWidth / 2, coverBoxHeight / 2 - 5);
          }else{
            let chr = contestTitle.split("");
            let temp = "";
            let row = [];
            for (let a = 0; a < chr.length; a++) {
              if (context.measureText(temp).width < (canvasWidth - 32)) {
                temp += chr[a];
              }
              else {
                a--;
                row.push(temp);
                temp = "";
              }
            }
            row.push(temp);
            rowCut = row.slice(0,2);
            for (let b = 0; b < rowCut.length; b++) {
              context.fillText(rowCut[b], canvasWidth / 2, coverBoxHeight / 2 - 5 + b*25);
            }
          }

          context.setFontSize(12);
          context.weight = "normal";
          context.setTextAlign('center');
          context.setTextBaseline('top');
          context.setFillStyle("#fff");
          let b = 0;
          if (rowCut.length){
            b = rowCut.length-1
          } 
          context.fillText(Store.cur_contest.hostUnit, canvasWidth / 2, coverBoxHeight / 2 + 5 + b*25);


          context.setFontSize(12);
          context.weight = "normal";
          context.setTextAlign('center');
          context.setTextBaseline('bottom');
          context.setFillStyle("#fff");
          context.fillText(Store.cur_contest.contestPropertyInfo.prizeMsg, canvasWidth / 2, coverBoxHeight - 12);

          let prizeIconLeft = (canvasWidth - context.measureText(Store.cur_contest.contestPropertyInfo.prizeMsg).width) / 2 - 23;
          let prizeIconTop = coverBoxHeight - 28;
          context.drawImage(prize_obj.res.path, prizeIconLeft, prizeIconTop, 17, 15);

          context.drawImage(logo_obj.res.path, 20, coverBoxHeight + 85, 139, 18);
          context.drawImage(erweima_obj.res.path, canvasWidth - 92, coverBoxHeight + 16, 72, 72);

          context.setFontSize(10);
          context.setTextAlign('right');
          context.setTextBaseline('top');
          context.setFillStyle("#525558");
          context.fillText('扫描或长按小程序码', canvasWidth - 11, coverBoxHeight + 93);

          context.draw(false, () => {
            setTimeout(function () {
              wx.canvasToTempFilePath({
                canvasId: 'myCanvas',
                fileType: 'jpg',
                success: function (res) {
                  wx.hideLoading();
                  me.setData({
                    canvasHidden: true,
                  });
                  wx.previewImage({
                    current: res.tempFilePath,
                    urls: [res.tempFilePath]
                  })
                }
              })
            }, 500);
          });

        });
      })
      
    })
  
    
  },

  selectCate:function(e){
    let item = e.currentTarget.dataset.item;
    if (item && item.id){
      this.hideModal(item.id);
      this.setData({
        selectedCategoryId: item.id,
        workSource: item.graphic ? 2 : item.workSource
      },function(){
        Store.setPhotoState({ photo: item.photo, groupPhoto: item.groupPhoto, graphic: item.graphic})
        app.globalData.selectedCategoryId = item.id;
      })
    }else{
      this.hideModal('noCategory');
      app.globalData.selectedCategoryId = '';
    }
    
  },
  setContestCategoryId:function(e){
    Store.setContestCategoryId(e);
  },

  _submitAction(e) {
    if (!isAuthorization(e)){
      return;
    }
    let me = this;

    LoginStore.validateLogin(function() {
      if (Store.cur_contest.state != 102) {
        //大赛状态不是征集中
        wx.showModal({
          title: '提示',
          content: '大赛不在征集中，无法提交作品！',
          showCancel: false,
          success: function (res) {

          }
        })
        return;
      }

      me.setData({
        showTheme: true
      })
    }.bind(this))
  },
  hideModal: function(p) {
    let childs = this.selectComponent("#choose");
    childs.closePop();
    setTimeout(() => {
      let obj={};
      if (this.data.showTheme){
        obj.showTheme = false;
      }
      if (this.data.showModalStatus){
        obj.showModalStatus = false;
      }else if(typeof(p) === "string"){
        obj.showModalStatus = true;
      }
     
      this.setData(obj);
    }, childs.data.time)
  },
  takePoto: function() {
    if (Store.cur_contest.id === '8731b65f749d4266bb0fbbc0278843cc'){
      wx.showModal({
        content: '请到500px网站/app上传视频参加活动',
        showCancel:false,
        success: function (res) {}
      });
      return;
    }
    Store.takePhoto((path)=>{
      this.uploadImage({
        filePath: path
      });
    })
  },
  uploadImage(opts) {
    UploadStore.setFilePath(opts.filePath);
    UploadStore.setSelectedCategoryId(this.data.selectedCategoryId);
    wx.navigateTo({
      url: '/pages/editPhoto/editPhoto'
    });
  },
  _selectMyphoto() {
    let getUrl = (resourceType) => {
      var urlParamstr = encode({
        access_token: LoginStore.userInfo.access_token,
        client_type: 1,
        resourceType: resourceType,
        contestId: Store.cur_contest.id
      });
      return `${proxy}/contest/v4/data/joinable?` + urlParamstr
    }
    let resourceType = '';
    if (Store.photo && !Store.groupPhoto){
      resourceType = '0'
    } else if (!Store.photo && Store.groupPhoto){
      resourceType = '2'
    } else if (Store.photo && Store.groupPhoto){
      resourceType = '0,2'
    } else if (Store.graphic){
      resourceType = '3'
    }
    if (Store.cur_contest.id === '8731b65f749d4266bb0fbbc0278843cc'){
      resourceType = '4'
    }
    PhotoselectStore.setAjaxUrl(getUrl(resourceType));
    wx.navigateTo({
      url: `/pages/photoselect/photoselect?fromContest=true`
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  afterOnLoad: function (options){
    let me = this;
    me.setData({
      options: options
    })
    wx.showLoading({
      title: 'loading...',
      mask: true
    });

    Store.reset();
    Store.getContestDetail(options, () => {
      wx.hideLoading();

      me.makeShareImg();

      let tabEl = this.selectComponent('#contestTab');
      tabEl.setTabs(Store.cur_contest.contestTabs, (item) => {
        this._tabclick({
          detail: item
        });
      });

      if (options.showTheme) {
        me._submitAction();
      };

      this.setData({
        appParams:JSON.stringify({
          category:"contestDetail",
          id: Store.cur_contest.id
        })
      })

    });
    
  },
  onLoad: function(options) {
    if (shareFlag){
      shareFlag=false
    }

    let me = this;
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      getparamstr(scene, function (paramStr){
        if (paramStr.search('&') != -1) {
          let sceneArray = paramStr.split("&");
          //小米大赛
          options.id = sceneArray[0];
          let qudao = sceneArray[1];
          //统计
          wx.request({
            url: `${proxy}/alilog/put`,
            data: {
              objId: 'contestXiaomi' + qudao
            },
            method:'POST',
            header: Object.assign({
              'content-type': 'application/x-www-form-urlencoded'
            }, reqHeader),
            success: function (res) {
              console.log(res);
            }
          });

        } else {
          options.id = paramStr;
        }
        me.afterOnLoad(options);
      })
    }else{
      me.afterOnLoad(options);
    }
    
  },
  
  _tabclick: function(e) {
    let item = e.detail;
    let categoryTab = this.selectComponent('#categoryTab');
    if (item.name == 'introduction'){
      wx.navigateTo({
        url: `/pages/out/out?url=${encodeURIComponent(Store.cur_contest.refer)}`
      })
    } else if (item.name == 'prizeWorks'){
      //优秀作品
      let tplTabs = item.groupNames.split(",");
      let prizeTabs = [];
      for (let value of tplTabs) {
        prizeTabs.push({
          name: value,
          type:"prizeWorks"
        })
      }
      categoryTab.setTabs(prizeTabs);
      let urlStr = `${proxy}/contest/v4/data/prizes?dataType=${item.name}`;
      Store.setPhotoListUrl(urlStr, { groupName: tplTabs[0]});
    }else{
      categoryTab.setTabs(Store.contestCategoriesArray);
      let urlStr = `${proxy}/contest/v4/data/works?dataType=${item.name}&resourceType=0,2,3,4`;
      Store.setPhotoListUrl(urlStr, {contestCategoryId: Store.contestCategoryId});
    }
    
  },
  toUserInfo : function(e){
    if (!isAuthorization(e)) {
      return;
    }
    LoginStore.validateLogin(()=>{
      let userId = LoginStore.userInfo.userId;
      let urlStr = '/pages/userInfo/userInfo?userId=' + userId;

      let pageList = getCurrentPages();
      if (pageList.length >= 8) {
        wx.redirectTo({
          url: urlStr,
        })
      } else {
        wx.navigateTo({
          url: urlStr
        });
      }
    });
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(options) {
    if (shareFlag) {
      shareFlag = false
    }
    //刷新
    if (this.data.freshMark == undefined || !this.data.freshMark){
      return;
    }

    if (this.selectComponent("#choose")){
      this.hideModal();
    }
    
    wx.showLoading({
      title: 'loading...',
      mask: true
    });

    let contestId = Store.cur_contest.id;
    Store.reset();
    Store.getContestDetail({ id: contestId}, () => {
      wx.hideLoading();

      let tabEl = this.selectComponent('#contestTab');
      tabEl.setTabs(Store.cur_contest.contestTabs, (item) => {
        this._tabclick({
          detail: item
        })
      });

    });

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      freshMark:false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    Store.nextPage();
  },

  /**
   * 用户点击右上角分享
   */
  makeShareImg:function() {
    let me = this;
    let cover_obj = {
      url: Store.cur_contest.appDetailUrl ? Store.cur_contest.appDetailUrl.baseUrl + '!wechat' : Store.cur_contest.appUrl.baseUrl + '!wechat'
    }
    let prize_obj = {
      url: 'https://node.500px.me/images/WeChat/quest.png'
    }
    async.forEach([cover_obj, prize_obj], (item, callback) => {
      wx.getImageInfo({
        src: item.url,
        success: function (res) {
          item.res = res;
          callback();
        },
        fail: function (e) {
          console.log(e)
        }
      });
    }, function () {
      let canvasWidth = app.globalData.screenWidth;;
      let canvasHeight = cover_obj.res.height / cover_obj.res.width * canvasWidth;

      me.setData({
        canvasHeight: canvasHeight,
        canvasHidden: false
      },()=>{
        var context = wx.createCanvasContext('myCanvas');

        context.drawImage(cover_obj.res.path, 0, 0, canvasWidth, canvasHeight);

        context.rect(0, 0, canvasWidth, canvasHeight)
        context.setFillStyle("rgba(0,0,0,0.5)");
        context.fill();

        context.setFontSize(20);
        context.weight = "bold";
        context.setTextAlign('center');
        context.setTextBaseline('bottom');
        context.setFillStyle("#fff");
        context.fillText(Store.cur_contest.title, canvasWidth / 2, canvasHeight / 2 - 5);

        context.setFontSize(12);
        context.weight = "normal";
        context.setTextAlign('center');
        context.setTextBaseline('top');
        context.setFillStyle("#fff");
        context.fillText(Store.cur_contest.contestPropertyInfo.prizeMsg, canvasWidth / 2, canvasHeight / 2 + 5);

        let prizeIconLeft = (canvasWidth - context.measureText(Store.cur_contest.contestPropertyInfo.prizeMsg).width) / 2 - 23;
        let prizeIconTop = canvasHeight / 2 + 3;
        context.drawImage(prize_obj.res.path, prizeIconLeft, prizeIconTop, 17, 15);

        context.draw(false,()=>{
          setTimeout(function() {
            wx.canvasToTempFilePath({
              canvasId: 'myCanvas',
              fileType: 'jpg',
              success: function (res) {
                me.setData({
                  canvasHidden: true,
                  shareImgurl: res.tempFilePath
                }, function () {
                  wx.hideLoading();
                  if (shareFlag) {
                    me.sharePopShow();
                  }
                })

              }
            })
          }, 500);
        });


      })

    });
    
    
  },
  onShareAppMessage: function() {
    let intro = Store.cur_contest.contestPropertyInfo.intro;
    if (intro){
      let key = intro.indexOf("。");
      intro = intro.substring(0, key);
    }else{
      intro = Store.cur_contest.title
    }
    
    let obj = {
      title: intro,
      path: `/pages/contest/contest?id=${Store.cur_contest.id}`
    }
    if (this.data.shareImgurl){
      obj.imageUrl=this.data.shareImgurl;
    }
    return obj
    
  }
}))